package edu.cuit.avatar;

import edu.cuit.avatar.common.JdbcHelper;

import java.sql.*;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/25 8:48
 */
public class CourseJdbcTest {

    public static void main(String[] args) {
        //insert();
        login("20000901001", "peppa");
        login("20000901001", "1' or true or '1");
    }

    public static boolean login(String ssn, String password){
        boolean result = false;
        //1.获取与数据库的连接
        var conn = JdbcHelper.getInstance().getConnection();
        try {
            //2.通过Connection创建PreparedStatement
            var sql = "select ssn, name, gender from student where ssn=? and password=?";
            var ptst = conn.prepareStatement(sql);
            //3.对sql参数进行设置
            ptst.setString(1, ssn);
            ptst.setString(2, password);
            //4.执行sql并且返回执行结果
            var rs = ptst.executeQuery();
            //5.处理执行结果
            if(rs.next()){
                //从结果集中获取结果
                System.out.println("ssn:" + rs.getString(1) + "  name:" + rs.getString("name") + "  gender:" + rs.getString("gender"));
                result = true;
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //6.确保资源的释放
            JdbcHelper.getInstance().free(conn);
        }
        return result;
    }




    public static void insert(){
        //1.获取与数据库的连接
        var conn = JdbcHelper.getInstance().getConnection();
        try {
            //2.通过Connection创建PreparedStatement
            var sql = "insert into course(name, credits, intro) values(?,?,?)";
            var ptst = conn.prepareStatement(sql);
            //3.对sql参数进行设置
            ptst.setString(1, "高等数学");
            ptst.setInt(2, 8);
            ptst.setString(3, "杨光明教授授课,需要抢座");
            //4.执行sql并且返回执行结果
            var result = ptst.executeUpdate();
            //5.处理执行结果
            if(result == 1)
                System.out.println("课程添加成功");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //6.确保资源的释放
            JdbcHelper.getInstance().free(conn);
        }

    }
}
